<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="crud.props.searchToggle">
        <!-- 搜索 -->
        <el-select v-model="query.daTaskId" clearable filterable class="filter-item" placeholder="选择任务">
          <el-option
            v-for="item in task.da_task"
            :key="item.id"
            :label="item.serialnumber"
            :value="item.id">
          </el-option>
        </el-select>
        <el-select v-model="query.daEquipmentId" clearable filterable class="filter-item" placeholder="选择设备">
          <el-option
            v-for="item in equipment.da_equipment"
            :key="item.id"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>
        <rrOperation :crud="crud" />
      </div>
      <!--如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->
      <subtaskOperation :permission="permission" />
      <!--表单组件-->
      <el-dialog :close-on-click-modal="false" :before-close="crud.cancelCU" :visible="crud.status.cu > 0" :title="crud.status.title" width="500px" @open="dialogOpen">
        <el-form ref="form" :model="form" :rules="rules" size="small" label-width="80px">
          <el-form-item label="任务" prop="daTaskId">
            <el-select v-model="form.daTaskId" filterable placeholder="请选择">
              <el-option
                v-for="item in task.da_task"
                :key="item.id"
                :label="item.serialnumber"
                :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="设备" prop="daEquipmentId">
            <el-select v-model="form.daEquipmentId" filterable placeholder="请选择" @change="selectChanged">
              <el-option
                v-for="item in equipment.da_equipment"
                :key="item.id"
                :label="item.name"
                :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="导入标签" prop="label">
            <el-input v-model="form.label" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="数据文件" prop="fileList">
            <el-upload
              v-model="form.dataFile.filenameArray"
              class="upload-demo"
              :disabled="disabledDataFile"
              :action="fileUrl"
              :headers="headers"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :before-upload="beforeUpload"
              :on-error="onError"
              :data="form"
              :before-remove="beforeRemove"
              :on-success="successEvent"
              :limit="1"
              :on-exceed="handleExceed"
              :file-list="form.dataFile.filenameArray" >
              <el-button size="small" type="primary" :disabled="disabledDataFile">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传csv,xls,xlsx文件，且不超过500kb</div>
            </el-upload>
          </el-form-item>
          <el-form-item  label="系统数据文件" prop="systemFilename" v-show="false">
            <el-input v-model="form.dataFile.systemFilename" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="crud.cancelCU">取消</el-button>
          <el-button :loading="crud.cu === 2" type="primary" @click="crud.submitCU">确认</el-button>
        </div>
      </el-dialog>
      <el-dialog title="确认预处理数据" width="90%" :visible="dialogVisible1" >
        <data01 :data01Data="data01Data"/>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible1 = false">取 消</el-button>
          <el-button type="primary" @click="dialogVisible1 = false">确 定</el-button>
        </span>
      </el-dialog>
      <el-dialog title="确认预处理数据" width="90%" :visible="dialogVisible2">
        <data02 :data02Data="data02Data" />
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible2 = false">取 消</el-button>
          <el-button type="primary" @click="dialogVisible2 = false">确 定</el-button>
        </span>
      </el-dialog>
      <!--表格渲染-->
      <el-table ref="table" v-loading="crud.loading" :data="crud.data" size="small" style="width: 100%;" @selection-change="crud.selectionChangeHandler">
        <el-table-column type="selection" width="55" />
        <el-table-column v-if="columns.visible('daTaskId')" prop="daTaskId" label="任务">
          <template slot-scope="scope">
            {{ task.label.da_task[scope.row.daTaskId] }}
          </template>
        </el-table-column>
        <el-table-column v-if="columns.visible('daEquipmentId')" prop="daEquipmentId" label="设备">
          <template slot-scope="scope">
            {{ equipment.label.da_equipment[scope.row.daEquipmentId] }}
          </template>
        </el-table-column>
        <el-table-column v-if="columns.visible('label')" prop="label" label="导入标签" />
        <el-table-column v-if="columns.visible('createUser')" prop="createUser" label="创建人" />
        <el-table-column v-if="columns.visible('createDate')" prop="createDate" label="创建时间">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createDate) }}</span>
          </template>
        </el-table-column>
        <el-table-column v-if="columns.visible('updateUser')" prop="updateUser" label="最后修改人" />
        <el-table-column v-if="columns.visible('updateDate')" prop="updateDate" label="最后修改时间">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.updateDate) }}</span>
          </template>
        </el-table-column>
        <el-table-column v-permission="['admin','daSubtask:edit','daSubtask:del']" label="操作" width="150px" align="center">
          <template slot-scope="scope">
            <udOperation
              :data="scope.row"
              :permission="permission"
            />
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <pagination />
    </div>
  </div>
</template>

<script>
import crudDaSubtask from '@/api/daSubtask'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import subtaskOperation from '@crud/SUBTASK.operation'
import udOperation from '@crud/UD.operation'
import pagination from '@crud/Pagination'
import data01 from '../data01/dialogIndex'
import data02 from '../data02/dialogIndex'
import { getToken } from '@/utils/auth'

// crud交由presenter持有
const defaultCrud = CRUD({ title: '数据导入', url: 'api/daSubtask', sort: 'id,desc', crudMethod: { ...crudDaSubtask }})
const defaultForm = { id: null, daTaskId: null, daEquipmentId: null, label: null, isDelete: null, createUser: null, createDate: null, updateUser: null, updateDate: null, dataFile: { systemFilename: null, filenameArray: [] } }
export default {
  name: 'DaSubtask',
  components: { pagination, subtaskOperation, rrOperation, udOperation, data01, data02 },
  mixins: [presenter(defaultCrud), header(), form(defaultForm), crud()],
  tasks: [],
  equipments: [],
  data() {
    return {
      permission: {
        add: ['admin', 'daSubtask:add'],
        edit: ['admin', 'daSubtask:edit'],
        del: ['admin', 'daSubtask:del']
      },
      rules: {
        daTaskId: [
          { required: true, message: '任务不能为空', trigger: 'blur' }
        ],
        daEquipmentId: [
          { required: true, message: '设备不能为空', trigger: 'blur' }
        ],
        label: [
          { required: true, message: '导入标签不能为空', trigger: 'blur' }
        ]
      },
      headers: {
        'Authorization': getToken()
      },
      dialogVisible1: false,
      dialogVisible2: false,
      fileUrl: '',
      disabledDataFile: true,
      data01Data: {},
      data02Data: {}
    }
  },
  methods: {
    // 获取数据前设置好接口地址
    [CRUD.HOOK.beforeRefresh]() {
      const query = this.query
      if (query.type && query.value) {
        this.crud.params[query.type] = query.value
      }
      return true
    },
    handleRemove(file, fileList) {
      console.log(file, fileList)
    },
    handlePreview(file) {
      console.log(file)
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
    },
    beforeRemove(file, fileList) {
      if(file.name){
        var filenameSuffix = file.name.substring(file.name.lastIndexOf("."));
        if(filenameSuffix.toLowerCase()== ".csv"
        ||filenameSuffix.toLowerCase()== ".xls"
        ||filenameSuffix.toLowerCase()== ".xlsx"){
          return this.$confirm(`确定移除 ${file.name}？`);
        }else{
          return true;
        }
      }
    },
    successEvent(response, file, fileList) {
      this.crud.form.dataFile.systemFilename = response.dataFile.systemFilename
      if (this.crud.form.daEquipmentId == 1) {
        this.data01Data = {"systemFilename":response.dataFile.systemFilename};
        this.dialogVisible1 = true
      }else if (this.crud.form.daEquipmentId == 2) {
        this.data02Data = {"systemFilename":response.dataFile.systemFilename};
        this.dialogVisible2 = true
      }
      
    },
    onError(response, file, fileList){
      var reg = /"resultMessage":"(.*)"}/;
      this.$notify({
        title: reg.exec(response)[1].trim(),
        type: 'error',
        duration: 2500
      })
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done()
        })
        .catch(_ => {})
    },
    selectChanged(value) {
      if (value == 1) {
        this.disabledDataFile = false
        this.fileUrl = process.env.VUE_APP_BASE_API+'/api/daSubtask/upload1'
      } else if(value == 2) {
        this.disabledDataFile = false
        this.fileUrl = process.env.VUE_APP_BASE_API+'/api/daSubtask/upload2'
      } else {
        this.disabledDataFile = true
        this.fileUrl = ''
      }
    },
    dialogOpen() {
      this.selectChanged(this.crud.form.daEquipmentId)
    },
    beforeUpload(file) {
      if(file.name){
        var filenameSuffix = file.name.substring(file.name.lastIndexOf("."));
        if(filenameSuffix.toLowerCase()== ".csv"
        ||filenameSuffix.toLowerCase()== ".xls"
        ||filenameSuffix.toLowerCase()== ".xlsx"){
          return true;
        }else{
          this.$notify({
            title: '上传图片必须是CSV/XLS/XLSX 格式!',
            type: 'error',
            duration: 2500
          })
          return false;
        }
      }
    }
  }
}
</script>

<style scoped>

</style>
